package com.kadron.application;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.transaction.Transaction;
import org.jboss.seam.transaction.UserTransaction;
import org.richfaces.event.FileUploadListener;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

import com.kadron.common.KConst;
import com.kadron.common.KIDGenerator;
import com.kadron.common.KInitParams;
import com.kadron.common.KUtil;
import com.kadron.dao.KApplicationDAO;
import com.kadron.dao.KImageDAO;
import com.kadron.entity.Application;
import com.kadron.entity.KApplicationImage;
import com.kadron.entity.KImage;
import com.kadron.exceptions.UploadImageException;
import com.kadron.manager.KMessageManager;

@AutoCreate
@Name("kApplicationManager")
@Scope(ScopeType.PAGE)
public class KApplicationManager extends KMessageManager implements Serializable,FileUploadListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4184026689307942094L;

	private static final Log log = LogFactory.getLog(KApplicationManager.class);
	
	private Application application; 
	private List<KImage> images = new LinkedList<KImage>();
	
	@In
	private KApplicationDAO applicationDAO;
	
	@In
	private KImageDAO imageDAO;
	
	@Create
	public void init() {
		Long applicationId = (Long) Component.getInstance("applicationId");
		if (applicationId == null) {
			applicationId = new Long(0);
		}
		if (applicationId > 0) {
			application = (Application) applicationDAO.find(applicationId, Application.class);
			loadImages();
		} else {
			application = new Application();
		}
	}
	
	public String save() {
		if (application == null) {
			bad(KConst.BAD_THING);
			return null;
		}
		if (log.isDebugEnabled()) {
			log.debug("Save Application applicationId="+application.getId());
		}
		applicationDAO.update(application);
		good();
		return "application";
	}

	public Application getApplication() {
		return application;
	}

	public void setApplication(Application application) {
		this.application = application;
	}

	public List<KImage> getImages() {
		return images;
	}

	public void setImages(List<KImage> images) {
		this.images = images;
	}
	
	public void loadImages() {
		images.clear();
		images = imageDAO.getApplicationImages(application.getId());
	}

	@Override
	public void processUpload(UploadEvent arg0) {
		UploadItem item = arg0.getUploadItem();
		if (item == null) {
			bad(KConst.BAD_THING);
			return;
		}
		int size = item.getFileSize();
		if (size > 1024000) {
			bad(KConst.BAD_THING);
			return;
		}
		String itemName = item.getFileName();
		byte[] data = new byte[4096];
		FileOutputStream outputStream = null;
		FileInputStream inputStream = null;
		String strDirectory = "";
		String imgPath = "";
		KApplicationImage image = new KApplicationImage(application.getId());
		UserTransaction transaction = null;
		try {
			transaction = Transaction.instance();
			strDirectory = KInitParams.WEBAPPS_PATH+KInitParams.IMG_PATH+"/app_"+application.getId();							
			imgPath = KInitParams.IMG_PATH+"/app_"+application.getId()+"/";							
			File directory = new File(strDirectory);
			if (!directory.exists()) {
				directory.mkdir();
			}
			
			String uuid = KIDGenerator.createUUID();
			image.setPath(imgPath);
			
			int IndexOf = itemName.lastIndexOf(".");
			String domainName = itemName.substring(IndexOf);
			if (log.isDebugEnabled()) {
				log.debug("domainName: " + domainName);							
			}
			if (KUtil.isEmpty(domainName)) {
				throw new UploadImageException("Domain name je prazno");
			} else if (!domainName.equalsIgnoreCase(".png") 
						&& !domainName.equalsIgnoreCase(".jpg")
						&& !domainName.equalsIgnoreCase(".JPG")
						&& !domainName.equalsIgnoreCase(".JPEG")
						) {
				throw new UploadImageException("Domain Name nije odgovarajuce");
			}
			String finalimage = uuid+domainName;
			if (log.isDebugEnabled()) {
				log.debug("Final Image===" + finalimage);							
			}
			
			image.setName(finalimage);
			image.setThumb(finalimage);
			if (images == null || images.isEmpty()) {
				image.setMain(true);
			}
			imageDAO.update(image);
			
			File file = new File(strDirectory+"/"+finalimage);
			outputStream = new FileOutputStream(file,true);
			inputStream = new FileInputStream(item.getFile());
			if (!file.exists()) {
				file.createNewFile();
				
			}
			int bit;
			while ((bit = inputStream.read(data)) != -1) {
				outputStream.write(data,0,bit);
			}
			inputStream.close();
			outputStream.flush();
			outputStream.close();
			transaction.commit();
			good();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (transaction != null) {					
					transaction.rollback();
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				inputStream.close();
				outputStream.close();				
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public void uploadThumb(UploadEvent arg0) {
		UploadItem item = arg0.getUploadItem();
		if (item == null) {
			bad(KConst.BAD_THING);
			return;
		}
		int size = item.getFileSize();
		Long imageId = (Long) arg0.getComponent().getAttributes().get("imageId");
		if (size > 1024000 || imageId == null || imageId <= 0) {
			bad(KConst.BAD_THING);
			return;
		}
		KApplicationImage kai = imageDAO.find(imageId, KApplicationImage.class);
		String itemName = item.getFileName();
		byte[] data = new byte[4096];
		FileOutputStream outputStream = null;
		FileInputStream inputStream = null;
		String strDirectory = "";
//		String imgPath = "";
		UserTransaction transaction = null;
		try {
			transaction = Transaction.instance();
			strDirectory = KInitParams.WEBAPPS_PATH+KInitParams.IMG_PATH+"/app_"+application.getId();							
//			imgPath = KInitParams.IMG_PATH+"/app_"+application.getId()+"/";							
			File directory = new File(strDirectory);
			if (!directory.exists()) {
				directory.mkdir();
			}
			
			String uuid = "t_"+KIDGenerator.createUUID();
			
			int IndexOf = itemName.lastIndexOf(".");
			String domainName = itemName.substring(IndexOf);
			if (log.isDebugEnabled()) {
				log.debug("domainName: " + domainName);							
			}
			if (KUtil.isEmpty(domainName)) {
				throw new UploadImageException("Domain name je prazno");
			} else if (!domainName.equalsIgnoreCase(".png") 
					&& !domainName.equalsIgnoreCase(".jpg")
					&& !domainName.equalsIgnoreCase(".JPG")
					&& !domainName.equalsIgnoreCase(".JPEG")
			) {
				throw new UploadImageException("Domain Name nije odgovarajuce");
			}
			String finalimage = uuid+domainName;
			if (log.isDebugEnabled()) {
				log.debug("Final Image===" + finalimage);							
			}
			
			kai.setThumb(finalimage);
			imageDAO.update(kai);
			
			File file = new File(strDirectory+"/"+finalimage);
			outputStream = new FileOutputStream(file,true);
			inputStream = new FileInputStream(item.getFile());
			if (!file.exists()) {
				file.createNewFile();
				
			}
			int bit;
			while ((bit = inputStream.read(data)) != -1) {
				outputStream.write(data,0,bit);
			}
			inputStream.close();
			outputStream.flush();
			outputStream.close();
			transaction.commit();
			good();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (transaction != null) {					
					transaction.rollback();
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			bad(KConst.BAD_THING);
		} finally {
			try {
				inputStream.close();
				outputStream.close();				
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public void mainImg(KApplicationImage img) {
		imageDAO.updateApplicationImageNotMain(img.getApplicationId());
		img.setMain(true);
		imageDAO.update(img);
		loadImages();
		good();
	}
	
	public void deleteImg(KApplicationImage img) {
		if (img == null) {
			bad(KConst.BAD_THING);
			return;
		}
		UserTransaction transaction = null;
		try {
			transaction = Transaction.instance();
			img = imageDAO.find(img.getId(), KApplicationImage.class);
			String strDirectory = KInitParams.WEBAPPS_PATH+KInitParams.IMG_PATH+"/app_"+application.getId();
			File file = new File(strDirectory+"/"+img.getName());
			File thumb = new File(strDirectory+"/"+img.getThumb());
			if (file.exists()) {
				boolean deleted = file.delete();
				if (!deleted) {
					log.error("Not deleted File: "+strDirectory+"/"+img.getName());
					bad("Not deleted File: "+strDirectory+"/"+img.getName());
					return;
				}
			}
			if (thumb.exists()) {
				boolean deleted = thumb.delete();
				if (!deleted) {
					log.error("Not deleted THUMB File: "+strDirectory+"/"+img.getThumb());
					bad("Not deleted THUMB File: "+strDirectory+"/"+img.getThumb());
					return;
				}
			}
			imageDAO.delete(img);
			transaction.commit();
			loadImages();
			good();			
		} catch (Exception e) {
			e.printStackTrace();
			if (transaction!=null) {
				try {
					transaction.rollback();					
				} catch (Exception e2) {
					log.error(e2);
				}
			}
		}
	}
	
	public void deleteThumb(KApplicationImage img) {
		if (img == null) {
			bad(KConst.BAD_THING);
			return;
		}
		UserTransaction transaction = null;
		try {
			transaction = Transaction.instance();
			img = imageDAO.find(img.getId(), KApplicationImage.class);
			String strDirectory = KInitParams.WEBAPPS_PATH+KInitParams.IMG_PATH+"/app_"+application.getId();
			File thumb = new File(strDirectory+"/"+img.getThumb());
			if (thumb.exists()) {
				boolean deleted = thumb.delete();
				if (!deleted) {
					log.error("Not deleted THUMB File: "+strDirectory+"/"+img.getThumb());
					bad("Not deleted THUMB File: "+strDirectory+"/"+img.getThumb());
					return;
				}
			}
			img.setThumb(null);
			imageDAO.update(img);
			transaction.commit();
			loadImages();
			good();			
		} catch (Exception e) {
			e.printStackTrace();
			if (transaction!=null) {
				try {
					transaction.rollback();					
				} catch (Exception e2) {
					log.error(e2);
				}
			}
		}
	}
	
}
